package com.queue.array;

// 数组模拟环形队列
public class CircleArrayQueue {
    // 队列最大长度
    private int maxSize;
    // 队列头指标,指向的元素既是队列的头部数据也是待取出的数据
    private int front;
    // 队列尾指标,指向待添加数据的位置
    private int rear;
    // 数组
    private int[] array;

    public CircleArrayQueue(int maxSize) {
        this.maxSize = maxSize;
        // 初始化队列头尾指标
        this.front = 0;
        this.rear = 0;

        this.array = new int[maxSize];
    }

    // 判断是否为满
    private boolean isFull() {
        return (rear + 1) % maxSize == front;
    }

    // 添加数据
    public void addData(int n) {
        if (isFull()) {
            throw new RuntimeException("队列满，无法添加数据");
        }
        this.array[rear] = n;
        rear = (rear + 1) % maxSize;
    }

    // 判断是否为空
    private boolean isEmpty() {
        return rear == front;
    }

    // 取出数据
    public int takeOutData() {
        if (isEmpty()) {
            throw new RuntimeException("队列空，无法取出数据");
        }
        int value = array[front];
        front = (front + 1) % maxSize;
        return value;
    }

    // 获取队列有效数据个数
    private int getSize() {
        return (rear - front + maxSize) % maxSize;
    }

    // 显示队列
    public void show() {
        if (isEmpty()) {
            throw new RuntimeException("队列空，无法显示数据");
        }
        for (int i = front; i < front + getSize(); i++) {
            System.out.printf("%d ", array[i % maxSize]);
        }
    }

    // 输出队列头元素
    public int peekHead() {
        if (isEmpty()) {
            throw new RuntimeException("队列空，无法获取头元素");
        }
        return array[front];
    }

}
